package com.kili.picture.tools.file;

import java.io.*;

/**
 * @author Jar
 * @Date 2019/4/3
 */
public class FileUtils {

    /**
     * 删除文件夹及里面的所有文件
     *
     * @param folderPath
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            File myFilePath = new File(folderPath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除文件夹里的所有文件
     *
     * @param path
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 复制单个文件(原名复制)
     *
     * @param oldPathFile 准备复制的文件源
     * @param targetPath  拷贝到新绝对路径带文件名(注：目录路径需带文件名)
     * @return
     */
    public static void copySingleFileTo(String oldPathFile, String targetPath) {
        InputStream inStream = null;
        FileOutputStream fs = null;
        int byteRead;

        try {
            File oldFile = new File(oldPathFile);

            if (oldFile.exists()) { //文件存在时
                inStream = new FileInputStream(oldPathFile); //读入原文件
                fs = new FileOutputStream(targetPath + oldFile.getName());

                byte[] buffer = new byte[1024];
                while ((byteRead = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteRead);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inStream != null) {
                    inStream.close();
                }

                if (fs != null) {
                    fs.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
